import React, {PureComponent} from "react";
import FormEditor from '../../components/FormEditor';
import {
    calculateFee,
    calculateOutFee,
    clearFee,
    findFeesByClientId,
    getBaoGuanFeeByClientId,
    getClientList2,
    getLines,
    updateOrderModel
} from "./actions";
import {connect} from "react-redux";
import {getPrincipal} from "../../lib/identity";
import {formatDate, formatStrToDate} from "../../lib/func";
import lodash from 'lodash';

class OrderInfoModal extends PureComponent {

    handleUpdateModel = order => {
        const {dispatch, model, lines = [], outFees, follows} = this.props;
        if (order.organizationId) {
            dispatch(getClientList2(order.organizationId));
        }
        dispatch(getLines({...order}));
        if (order.clientId !== undefined && order.clientId !== model.clientId) {
            delete order.originDestPlace;
            delete model.originDestPlace;
            delete model.carrierDeparturePort;
            dispatch(findFeesByClientId(order.clientId));
            dispatch(getBaoGuanFeeByClientId(order.clientId));
        }
        if (order.originDestPlace && order.originDestPlace.length > 0) {
            const arr = order.originDestPlace.split("-");
            order.originPlace = arr[0];
            order.destPlace = arr[1];
            const found = lines.find(item => item.originPlace === order.originPlace &&
                item.destPlace === order.destPlace && item.calculateType === order.calculateType);
            if (found && order.carrierDeparturePort === undefined) {
                order.carrierDeparturePort = found.departurePort;
            }
        }
        // 计算时效
        if (!lodash.isNil(order.actDepartureTime) && follows !== null && follows !== undefined && follows.length > 0 && !lodash.isNil(follows[0].arriveTime)) {
            // 算出时效
            const date1 = formatStrToDate(order.actDepartureTime);
            const date2 = formatStrToDate(follows[0].arriveTime);
            follows[0].aging = date2.diff(date1, 'day');
        }
        // 计算应收
        if (order.clientId && order.businessCode && order.calculateType && order.originPlace && order.destPlace && order.preDepartureTime) {
            order.grossWeight = order.goodsWeight;
            order.noTips = true;
            order.calculateTime = formatDate(order.preDepartureTime);
            // 清空应付费用,重新计算
            dispatch(clearFee());
            dispatch(calculateFee({...order}));
            // 重新刷新应付费用，只有费用小于等于0才会触发修改，这样做的目的是如果某一个费用因为某些原因修改了，但是在编辑订单是会触发二次计费，会把前面手动更改的覆盖
            outFees.forEach(item => {
                if (item.carrierId) {
                    dispatch(calculateOutFee({...order, ...item, noTips: true}));
                }
            });
        }
        // 计算超期天数
        if (order.orderArriveTime && order.orderLeaveTime) {
            const date1 = formatStrToDate(order.orderArriveTime);
            const date2 = formatStrToDate(order.orderLeaveTime);
            order.orderBeyondDays = date2.diff(date1, 'day') + 1;
        }
        // 计算用箱天数
        if (order.packageReturnDate && order.pickDate) {
            const date1 = formatStrToDate(order.packageReturnDate);
            const date2 = formatStrToDate(order.pickDate);
            order.packageUseDays = date1.diff(date2, 'day') + 1;
        }
        dispatch(updateOrderModel({...model, ...order, "id": model.id}));

    };

    render() {
        const {model, clientList, organizations, businessCodeList, calculateType, cabinetTypeList, lines = [], goods, bgTypes, coachList} = this.props;
        const originDestPlaceList = [];
        lines.forEach(item => {
            const originDestPlace = item.originPlace + "-" + item.destPlace;
            const found = originDestPlaceList.find(item => item.value === originDestPlace);
            if (!found) {
                originDestPlaceList.push({label: originDestPlace, value: originDestPlace});
            }
        });
        // 检查是否有费用锁定
        let feeHasLock = false;
        model.feeList && model.feeList.forEach(item => {
            if (item.status === "LOCK") {
                feeHasLock = true;
            }
        });
        const schema = [
            {
                title: '基础信息',
                fields: [
                    {
                        field: 'clientId',
                        title: '客户',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: clientList,
                            labelField: "name",
                            valueField: "id"
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择客户'}]
                        }
                    }, {
                        field: 'businessCode',
                        title: '业务类型',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: businessCodeList,
                            labelField: "name",
                            valueField: "name"
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择业务类型'}]
                        }
                    }, {
                        field: 'calculateType',
                        title: '计费方式',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: calculateType
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择计费方式'}]
                        }
                    }, {
                        field: 'bookName',
                        title: '订舱人',
                        readonly: feeHasLock,
                        type: 'text'
                    }, {
                        field: 'bookNumber',
                        title: '订舱号',
                        readonly: feeHasLock,
                        type: 'text'
                    }, {
                        field: 'pickDate',
                        title: '提货日期',
                        readonly: feeHasLock,
                        type: 'date'
                    }, {
                        field: 'pickPlace',
                        title: '提货地点',
                        readonly: feeHasLock,
                        type: 'text'
                    }, {
                        field: 'cabinetType',
                        title: '柜型',
                        type: 'autoComplete',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: cabinetTypeList
                        }
                    }, {
                        field: 'preDepartureTime',
                        title: '班列日期',
                        readonly: feeHasLock,
                        type: 'date'
                    }, {
                        field: 'actDepartureTime',
                        title: '发车日期',
                        readonly: feeHasLock,
                        type: 'date'
                    }, {
                        field: 'quantity',
                        title: '数量',
                        readonly: feeHasLock,
                        type: 'number'
                    }, {
                        field: 'volume',
                        title: '货物体积(m³)',
                        readonly: feeHasLock,
                        type: 'number'
                    }, {
                        field: 'customsType',
                        title: '报关方式',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: bgTypes,
                            labelField: "name",
                            valueField: "name"
                        }
                    }, {
                        field: 'goodsName',
                        title: '货物品类',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: goods,
                            labelField: "name",
                            valueField: "name"
                        }
                    }, {
                        field: 'goodsDetailName',
                        title: '货物品名',
                        readonly: feeHasLock,
                        type: 'text'
                    }, {
                        field: 'goodsWeight',
                        title: '货物重量(KG)',
                        readonly: feeHasLock,
                        type: 'number',
                    }, {
                        field: 'originDestPlace',
                        title: '线路',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: originDestPlaceList
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择线路'}]
                        }
                    }, {
                        field: 'carrierDeparturePort',
                        title: '出境口岸',
                        type: 'listSelector',
                        readonly: feeHasLock,
                        controlProps: {
                            dataSource: coachList,
                            labelField: "name",
                            valueField: "name"
                        }
                    }
                    /*, {
                        field: 'orderArriveTime',
                        title: 'ATA到达日期',
                        readonly: model.settlement === "已结算",
                        type: 'date'
                    }*/
                    , {
                        field: 'orderLeaveTime',
                        title: '境外提重日期',
                        readonly: model.settlement === "已结算",
                        type: 'date'
                    }, {
                        field: 'orderBeyondDays',
                        title: '超期天数(天)',
                        readonly: true
                    }, {
                        field: 'packageReturnDate',
                        title: '还箱日期',
                        readonly: true,
                        type: 'date'
                    }, {
                        field: 'packageUseDays',
                        title: '用箱天数(天)',
                        readonly: true,
                        type: 'date'
                    }, {
                        field: 'remark',
                        title: '备注',
                        readonly: model.settlement === "已结算",
                        type: 'textArea'
                    }
                ]
            }];
        if (getPrincipal().admin) {
            schema[0].fields.splice(0, 0, {
                field: 'organizationId',
                title: '所属机构',
                type: 'treeSelector',
                readonly: feeHasLock,
                controlProps: {
                    treeData: organizations,
                    labelField: "name",
                    valueField: "id",
                    treeCheckable: false
                },
                fieldOptions: {
                    rules: [{required: true, message: '请选择所属机构'}]
                }
            });
        }
        return (
            <FormEditor
                schema={schema}
                column={3}
                defaultReadonly={model.status === 'CONFIRMED'}
                showActionBar={false}
                defaultValues={model}
                onChange={this.handleUpdateModel}
            />
        );
    }
}

const mapStateToProps = state => {
    return {
        clientList: state.zadOrder.list.clientList,
        carrierList: state.home.carriers,
        currencyList: state.zadOrder.list.currencyList,
        calculateType: state.common.calculateType,
        cabinetTypeList: state.common.cabinetTypeList,
        transportTypeList: state.zadOrder.list.transportTypeList,
        coachList: state.zadOrder.list.coachList,
        businessCodeList: state.zadOrder.list.businessCodeList,
        organizations: state.home.organizations,
        goods: state.goods.list.dataSource,
        bgTypes: state.bgType.list.dataSource,
        outFees: state.zadOrder.orderOutFee.feeList,
        lines: state.zadOrder.lines.lines,
        follows: state.zadOrder.orderFollows.follows
    };
};

export default connect(mapStateToProps)(OrderInfoModal);
